package cn.com.winning.ecare.activity;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Rect;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.view.Display;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;
import cn.com.winning.ecare.common.BtoECalendarDialog;
import cn.com.winning.ecare.common.MyApplication;
import cn.com.winning.ecare.common.MyTimeUtil;
import cn.com.winning.ecare.expandable.ActionSlideExpandableListView;
import cn.com.winning.ecare.utils.DisplayUtil;
import cn.com.winning.ecare.utils.HTTPGetTool;
import cn.com.winning.ecare.utils.StringUtil;
import cn.com.winning.ecare.utils.URLUtils;
import cn.com.winning.ecare.utils.UserRecord;
import cn.com.winning.ecare.widgets.CustomProgressDialog;
import cn.com.winning.ecare.widgets.InnerListView;

/**
 * 检查报告
 */

public class TjbgActivity extends Activity
{

	private ActionSlideExpandableListView list_main;
	private TextView content, item, updateTime;
	private List<Map<String, Object>> listmain = new ArrayList<Map<String, Object>>();
	private List<Map<String, Object>> listsub = new ArrayList<Map<String, Object>>();
	private List<Object> children = new ArrayList<Object>();
	MyMainAdapter mainAdapter = null;
	MySubAdapter subAdapter = null;
	MyApplication myApplication;
	CustomProgressDialog proDialog;// 加载框
	TjbgActivity oThis = this;
	private static final String[] s = { "zs", "jy" };
	private static final String[] s_name = { "检查综述", "医生建议" };
	static int screenheight;
	static int screenwidth;
	private ImageButton menuButton;

	private ImageButton btnSearch;// 日期选择按钮
	private LinearLayout layout;
	private int height, statusBarHeight;
	private String startDate = "", endDate = "";
	private TextView startDateText, endDateText;

	@Override
	protected void onCreate(Bundle savedInstanceState)
	{
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.tjbg);
		myApplication = (MyApplication) getApplication();
		myApplication.addActivity(this);
		myApplication.getUserRecords().setUsername(myApplication.getAccount());
		myApplication.getUserRecords().setModule("TjbgActivity@体检报告");
		UserRecord.getInstance(myApplication.getUserRecords()).init();
		findViews();
		getInfo();
		setListener();
	}

	private void findViews()
	{
		list_main = (ActionSlideExpandableListView) findViewById(R.id.list);
		startDateText = (TextView) this.findViewById(R.id.startDateText);
		endDateText = (TextView) this.findViewById(R.id.endDateText);
		updateTime = (TextView) this.findViewById(R.id.updateTime);
		updateTime.setText("服务器最新数据同步于:"
				+ MyTimeUtil.GetSysDate(MyTimeUtil.yyyy_MM_dd_, MyTimeUtil.DateToStr(MyTimeUtil.yyyy_MM_dd_, new Date()), 0, 0, -14));
		// 主菜单配置信息传递到下一页面

		// 接受参数，主要用于日期选择后的日期获取，然后再传入每个tab
		// Intent intent = getIntent();
		// String startDate1 = intent.getStringExtra("startDate");
		// String endDate1 = intent.getStringExtra("endDate");
		// if((startDate1==null||"".equals(startDate1))&&(endDate1==null||"".equals(endDate1))){
		// //初次打开，没有选择日期
		Date now = new Date();
		SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
		startDate = simpleDateFormat.format(now);// 默认当天
		endDate = simpleDateFormat.format(now);
		// }else{
		// //选择的日期赋值
		// startDate = startDate1;
		// endDate = endDate1;
		// }
		// 设置初始化时间
		startDateText.setText(startDate);
		endDateText.setText(endDate);
		menuButton = (ImageButton) findViewById(R.id.menuButton);

		menuButton.setOnClickListener(new OnClickListener()
		{
			@Override
			public void onClick(View v)
			{

				oThis.onBackPressed();
			}
		});

		btnSearch = (ImageButton) this.findViewById(R.id.searchButton);
		layout = (LinearLayout) this.findViewById(R.id.jclayout);
	}

	private void setListener()
	{
		btnSearch.setOnClickListener(new View.OnClickListener()
		{

			@Override
			public void onClick(View v)
			{
				// TODO Auto-generated method stub
				initDateDialog();

			}
		});
		startDateText.setOnClickListener(new View.OnClickListener()
		{

			@Override
			public void onClick(View v)
			{
				initDateDialog();
			}
		});

		endDateText.setOnClickListener(new View.OnClickListener()
		{

			@Override
			public void onClick(View v)
			{
				initDateDialog();
			}
		});

	}

	private void initDateDialog()
	{
		// 初始化一个自定义的Dialog
		final BtoECalendarDialog dialog = new BtoECalendarDialog(oThis, R.style.MyDialog, startDateText.getText().toString(),
				endDateText.getText().toString());
		// 获取状态栏高度
		Rect frame = new Rect();
		getWindow().getDecorView().getWindowVisibleDisplayFrame(frame);
		statusBarHeight = frame.top;
		Log.i("aaa", "statusBarHeight :" + statusBarHeight);
		// 获取layout高度
		height = layout.getHeight();
		dialog.show();
		Window mWindow = dialog.getWindow();
		WindowManager windowManager = getWindowManager();
		Display display = windowManager.getDefaultDisplay();
		WindowManager.LayoutParams lp = mWindow.getAttributes();
		lp.x = 0;
		lp.y = height + statusBarHeight;
		lp.width = (int) (display.getWidth()); // 设置宽度
		lp.height = (int) (display.getHeight()) - height - statusBarHeight;// 设置高度
		mWindow.setAttributes(lp);

		Button btnok = (Button) dialog.findViewById(R.id.btnok);
		Button btncancel = (Button) dialog.findViewById(R.id.btncancel);

		btnok.setOnClickListener(new View.OnClickListener()
		{

			@Override
			public void onClick(View v)
			{
				// TODO Auto-generated method stub
				// 选择开始日期
				TextView startDate1 = (TextView) dialog.findViewById(R.id.tvSelectedstart);
				// 选择结束日期
				TextView endDate2 = (TextView) dialog.findViewById(R.id.tvSelectedend);
				String sd = startDate1.getText().toString();
				String ed = endDate2.getText().toString();

				dialog.dismiss();
				// proDialog = CustomProgressDialog.createDialog(othis);
				// proDialog.setMessage("数据加载中...");
				// proDialog.show();
				// proDialog.setCanceledOnTouchOutside(false);

				// 传入选择的日期，重新打开ReportActivity(要同时给tabhost中的两个tab页传入参数，暂无好方法，暂重刷主页面，同时传参)
				// Intent intent = getIntent();
				// intent.putExtra("startDate", sd);
				// intent.putExtra("endDate", ed);
				// intent.setClass(oThis, TjbgActivity.class);
				// startActivity(intent);
				// oThis.finish();
				startDate = sd;
				endDate = ed;
				startDateText.setText(sd);
				endDateText.setText(ed);
				getInfo();
			}
		});

		btncancel.setOnClickListener(new View.OnClickListener()
		{

			@Override
			public void onClick(View v)
			{
				// TODO Auto-generated method stub
				dialog.dismiss();
			}
		});
	}

	Handler myHandler = new Handler()
	{
		@Override
		public void handleMessage(Message msg)
		{
			// TODO Auto-generated method stub
			super.handleMessage(msg);
			switch (msg.what)
			{
				case -1:
					if (proDialog != null && proDialog.isShowing())
					{
						proDialog.dismiss();
					}
					Toast.makeText(oThis, (String) msg.obj, Toast.LENGTH_SHORT).show();
					break;
				case 0:
					if (proDialog != null && proDialog.isShowing())
					{
						proDialog.dismiss();
					}
					Map<String, Object> map = (Map<String, Object>) msg.obj;
					listmain = (List<Map<String, Object>>) map.get("tempmain");
					children = (List<Object>) map.get("tempchildren");
					if (mainAdapter == null)
					{
						mainAdapter = new MyMainAdapter();
					}
					list_main.setAdapter(mainAdapter);
					mainAdapter.notifyDataSetChanged();
					break;
				case 1:
					break;
				case 2:
					break;
				default:
					break;
			}
		}
	};

	private void getInfo()
	{
		proDialog = CustomProgressDialog.createDialog(oThis);
		proDialog.setMessage("数据加载中...");
		proDialog.show();
		proDialog.setCanceledOnTouchOutside(false);
		// 这里单开一个线程和后台数据交互
		new Thread(new LoadData()).start();

	}

	class LoadData implements Runnable
	{

		public void run()
		{
			// TODO Auto-generated method stub
			Looper.prepare();
			initData();
			Looper.loop();

		}

	}

	private void initData()
	{
		try
		{
			Message msg = myHandler.obtainMessage();
			if (StringUtil.isNotEmpty(endDate))
			{
				if (MyTimeUtil.getDaysOfTowDiffDate(endDate, MyTimeUtil.DateToStr(MyTimeUtil.yyyy_MM_dd, new Date())) < 14)
				{
					endDate = MyTimeUtil.GetSysDate(MyTimeUtil.yyyy_MM_dd, MyTimeUtil.DateToStr(MyTimeUtil.yyyy_MM_dd, new Date()), 0, 0,
							-14);
				}
			}
			// Intent intent = getIntent();
			// String startDate = intent.getStringExtra("startDate");
			// String endDate = intent.getStringExtra("endDate");
			List<NameValuePair> ls = new ArrayList<NameValuePair>();
			ls.add(new BasicNameValuePair("userid", myApplication.getAccount() == null ? "" : myApplication.getAccount()));
			ls.add(new BasicNameValuePair("sfzh", myApplication.getSfzh()));
			ls.add(new BasicNameValuePair("zsxm", myApplication.getHzxm()));
			// ls.add(new BasicNameValuePair("sjh", myApplication.getSjh()));
			// ls.add(new BasicNameValuePair("startdate", startDate));
			// ls.add(new BasicNameValuePair("enddate", endDate));
			// ls.add(new BasicNameValuePair("sfzh", "320421195903117017"));
			// ls.add(new BasicNameValuePair("zsxm", "陈国文"));
			ls.add(new BasicNameValuePair("sjh", myApplication.getSjh()));
			ls.add(new BasicNameValuePair("startdate", startDate));
			ls.add(new BasicNameValuePair("enddate", endDate));
			JSONObject json = HTTPGetTool.getTool().post(URLUtils.HOST + URLUtils.URLFINDTJBH, ls);
			JSONArray jsonArr;
			List<Map<String, Object>> tempmain = new ArrayList<Map<String, Object>>();
			List<Object> tempchildren = new ArrayList<Object>();
			Map<String, Object> tempmap = new HashMap<String, Object>();
			if (json != null)
			{
				if (json.getBoolean("success"))
				{
					if (new JSONArray(json.getString("ls")).length() > 0)
					{
						jsonArr = new JSONArray(json.getString("ls"));
						List<Map<String, Object>> list;
						for (int i = 0; i < jsonArr.length(); i++)
						{
							JSONObject obj_main = jsonArr.getJSONObject(i);
							Map<String, Object> map_main = new HashMap<String, Object>();
							map_main.put("id", obj_main.getString("tjbh"));
							map_main.put("bglx", "体检报告");
							map_main.put("bgid", obj_main.getString("tjbh"));
							map_main.put("jcsj", obj_main.getString("tjrq"));
							map_main.put("hzxm", obj_main.getString("xm"));
							map_main.put("ch", "");
							map_main.put("sqys", obj_main.getString("jcys"));
							map_main.put("bgys", obj_main.getString("jcys"));
							map_main.put("shys", obj_main.getString("jcys"));
							// map_main.put("userid", obj_main.getString("userid"));
							list = new ArrayList<Map<String, Object>>();
							for (int j = 0; j < s.length; j++)
							{
								Map<String, Object> map_sub = new HashMap<String, Object>();
								map_sub.put(s[j], obj_main.getString(s[j]));
								list.add(map_sub);
							}

							tempmain.add(map_main);
							tempchildren.add(list);
						}
						msg.what = 0;
						tempmap.put("tempmain", tempmain);
						tempmap.put("tempchildren", tempchildren);
						msg.obj = tempmap;
					}
					else
					{
						msg.what = -1;
						msg.obj = "暂无数据";
					}

				}
				else
				{
					msg.what = -1;
					msg.obj = "暂无数据";
				}
			}
			else
			{
				msg.what = -1;
				msg.obj = "网络连接失败!";
			}
			myHandler.sendMessage(msg);
		}
		catch (Exception e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

	/**
	 * 自定义listview布局显示内容
	 * 
	 * @author zjj
	 */
	class MyMainAdapter extends BaseAdapter
	{

		public int getCount()
		{
			// TODO Auto-generated method stub
			return listmain.size();
		}

		public Object getItem(int position)
		{
			// TODO Auto-generated method stub
			return listmain.get(position);
		}

		public long getItemId(int position)
		{
			// TODO Auto-generated method stub
			return position;
		}

		public View getView(final int position, View convertView, ViewGroup parent)
		{
			// TODO Auto-generated method stub
			View view = convertView;
			Map<String, Object> map = (Map<String, Object>) getItem(position);
			view = LayoutInflater.from(getApplicationContext()).inflate(R.layout.tjbg_main, null);
			TextView reportName = (TextView) view.findViewById(R.id.reportName);
			TextView reportTime = (TextView) view.findViewById(R.id.reportTime);

			TextView reportDoctor = (TextView) view.findViewById(R.id.reportDoctor);
			TextView reportDetail = (TextView) view.findViewById(R.id.reportDetail);
			reportDetail.setOnClickListener(new OnClickListener()
			{

				@Override
				public void onClick(View v)
				{
					String tjbh = String.valueOf(listmain.get(position).get("id"));
					Intent intent = new Intent(oThis, TjbgmxActivity.class);
					Bundle bundle = new Bundle();
					bundle.putString("tjbh", tjbh);
					intent.putExtras(bundle);
					startActivity(intent);
				}
			});
			reportName.setText(map.get("bglx").toString());
			String time = map.get("jcsj").toString();
			// time = map.get("jcsj").toString().substring(0, 4) + "-" +
			// map.get("jcsj").toString().substring(4, 6) + "-"
			// + map.get("jcsj").toString().substring(6, 8);
			reportTime.setText(time);

			reportDoctor.setText(map.get("bgys").toString());

			InnerListView list_sub = (InnerListView) view.findViewById(R.id.list_tjbg_sub);
			ScrollView scroll_view = (ScrollView) view.findViewById(R.id.scroll_view);
			listsub = (List<Map<String, Object>>) children.get(position);
			subAdapter = new MySubAdapter(oThis, listsub);
			list_sub.setAdapter(subAdapter);
			list_sub.setParentScrollView(scroll_view);
			list_sub.setMaxHeight(DisplayUtil.dip2px(oThis, 300));
			return view;
		}

	}

	/**
	 * 自定义listview布局显示内容
	 */
	class MySubAdapter extends BaseAdapter
	{

		Context context;
		List children;

		public MySubAdapter(Context context, List children)
		{
			super();
			this.context = context;
			this.children = children;
		}

		public int getCount()
		{
			// TODO Auto-generated method stub
			return children.size();
		}

		public Object getItem(int position)
		{
			// TODO Auto-generated method stub
			return children.get(position);
		}

		public long getItemId(int position)
		{
			// TODO Auto-generated method stub
			return position;
		}

		public View getView(int position, View convertView, ViewGroup parent)
		{
			// TODO Auto-generated method stub
			View view = convertView;
			Map<String, Object> map = (Map<String, Object>) getItem(position);
			view = LayoutInflater.from(getApplicationContext()).inflate(R.layout.tjbg_sub, null);

			item = (TextView) view.findViewById(R.id.item);
			item.setText(s_name[position]);

			content = (TextView) view.findViewById(R.id.content);
			String temp = map.get(s[position]).toString();
			if (temp.equals(""))
			{
				content.setVisibility(View.GONE);
			}
			else
			{
				content.setText(temp);
			}
			return view;
		}

	}

}
